{% import 'macro/svg.html' as SVG %}
{% import 'macro/form.html' as FORM %}
{% import 'macro/oops.html' as OOPS %}
<div class="container-xl">
  <!-- Page title -->
  <div class="page-header d-print-none">
    <div class="row align-items-center">
      <div class="col">
        <h2 class="page-title">
          插件
        </h2>
      </div>
      <div class="col-auto ms-auto d-print-none">
        <div class="btn-list">
          <a href="javascript:show_plugin_apps_modal()" class="btn btn-primary d-none d-sm-inline-block">
            {{ SVG.apps() }}
            插件市场
          </a>
          <a href="javascript:show_plugin_apps_modal()" class="btn btn-primary d-sm-none btn-icon">
            {{ SVG.apps() }}
          </a>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- 业务页面代码 -->
{% if Count > 0 %}
  <div class="page-body">
    <div class="container-xl">
      <div class="d-grid gap-3 grid-normal-card">
      {% for Id, Plugin in Plugins.items() %}
        <a class="card card-link-pop p-0 rounded-3 overflow-hidden" href="#" data-bs-toggle="modal" data-bs-target="#modal-plugin-{{ Id }}">
          <div class="card-cover card-cover-blurred text-center {% if Plugin.color.startswith('bg-') %}{{ Plugin.color }}{% endif %}"
            {% if Plugin.color.startswith('#') %}style="background-color: {{ Plugin.color }}"{% endif %}>
            <span class="avatar avatar-xl avatar-thumb avatar-rounded"
                {% if Plugin.icon and not Plugin.icon.startswith('http') %}
                  style="background-image: url('../static/img/plugins/{{ Plugin.icon }}')"
                {% elif Plugin.icon %}
                  style="background-image: url('{{ Plugin.icon }}')"
                {% endif %}
            >
            {% if not Plugin.icon %}
              {{ Plugin.name|first }}
            {% endif %}
            </span>
          </div>
          <div class="card-body text-center">
            <div class="card-title mb-1">{% if Plugin.state %}<span class="badge bg-green"></span>{% endif %} {{ Plugin.name }}</div>
            <div class="text-muted">{{ Plugin.desc }}</div>
          </div>
        </a>
      {% endfor %}
      </div>
    </div>
  </div>
{% else %}
  {{ OOPS.empty('没有插件', '没有安装任何插件，请前往插件市场选择安装。') }}
{% endif %}
{% for Id, Plugin in Plugins.items() %}
  <plugin-modal
    plugin-id="{{ Id }}"
    plugin-name="{{ Plugin.name }}"
    plugin-config='{{ Plugin.config|tojson|safe }}'
    plugin-fields='{{ Plugin.fields|tojson|safe }}'
    plugin-prefix="{{ Plugin.prefix }}"
    plugin-page="{{ Plugin.page }}"
  >
  </plugin-modal>
{% endfor %}
<div class="modal modal-blur fade" id="modal-plugin-apps" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">插件市场</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="d-grid gap-3 grid-normal-card align-items-start" id="plugin_apps_content">
        </div>
      </div>
    </div>
  </div>
</div>
<div class="modal modal-blur fade" id="modal-plugin-page" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="plugin_page_title"></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div id="plugin_page_content">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="modal_plugin_page_btn">确定</button>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
  // 保存配置
  function save_config(id, prefix, func) {
    let params = input_select_GetVal(`modal-plugin-${id}`, prefix);
    let selectgroup_config = {};
    $(`#modal-plugin-${id} div[class^='form-selectgroup']`).each(function(){
      let name = $(this).attr("id");
      selectgroup_config[name.replace(prefix, "")] = select_GetSelectedVAL(name);
    })
    params = {...params, ...selectgroup_config}
    console.log(params)
    ajax_post("update_plugin_config", {plugin: id, config: params}, func);
  }

  //保存配置、关闭和刷新页面
  function save_plugin_config(plugin, prefix) {
    $("#modal-plugin-" + plugin).modal('hide');
    save_config(plugin, prefix, function (ret) {
      window_history_refresh();
    });
  }

  // 显示插件市场页面
  function show_plugin_apps_modal() {
    // 获取插件列表
    ajax_post("get_plugin_apps", {}, function(ret){
      if (ret.result) {
        $("#plugin_apps_content").empty();
        for (let pid in ret.result) {
          let plugin = ret.result[pid];
          let count = ret.statistic[pid];
          let plugin_html = `
            <div class="card card-link-pop card-borderless p-0 shadow-sm rounded-3 overflow-hidden" href="javascript:void(0)">
              <div class="card-cover card-cover-blurred text-center ${plugin.color.startsWith('bg-') ? plugin.color:''}"
                ${plugin.color.startsWith('#') ? `style="background-color: ${plugin.color}"` : ''}
              >
                <span class="avatar avatar-xl avatar-thumb avatar-rounded"
                    style="background-image: url('../static/img/plugins/${plugin.icon}')"
                >
                </span>
                ${count ? `<span class="badge position-absolute" style="top: 10px; right: 10px;">${count}</span>` : ''}
              </div>
              <div class="card-body text-start">
                <div class="card-title mb-1">${plugin.name}</div>
                <div class="text-muted"><strong>描述：</strong>${plugin.desc}</div>
                <div class="text-muted mt-1"><strong>作者：</strong>
                ${plugin.author_url ? `<a href="${plugin.author_url}" target="_blank">${plugin.author}</a>`
                  : `<span class="text-muted">${plugin.author}</span>`}
                </div>
              </div>
              <div class="d-flex">
                ${plugin.installed ? `
                  <a href="javascript:uninstall_plugin('${pid}', '${plugin.name}')" class="card-btn text-danger">
                    {{ SVG.trash('me-2') }}
                     卸载
                  </a>
                  ` : `
                  <a href="javascript:install_plugin('${pid}', '${plugin.name}')" class="card-btn">
                    {{ SVG.cloud_download('me-2') }}
                     安装
                  </a>
                  `}
              </div>
            </div>
          `;
          $("#plugin_apps_content").append(plugin_html);
        }
        $("#modal-plugin-apps").modal('show');
      }
    });
  }

  // 显示插件页面
  function show_plugin_extra_page(id) {
    ajax_post("get_plugin_page", {id: id}, function(ret){
      if (ret.code === 0) {
        $("#modal-plugin-" + id).modal('hide');
        $("#plugin_page_title").text(ret.title);
        $("#plugin_page_content").html(ret.content);
        if (ret.func) {
          $("#modal_plugin_page_btn").unbind('click').click(function(){
            eval(ret.func);
          });
        } else {
          $("#modal_plugin_page_btn").unbind('click').click(function(){
            $('#modal-plugin-page').modal('hide');
          });
        }
        $("#modal-plugin-page").modal('show');
      }
    });
  }

  // 安装插件
  function install_plugin(id, name) {
    ajax_post("install_plugin", {id: id}, function(ret){
      $("#modal-plugin-apps").modal('hide');
      if (ret.code === 0) {
        show_success_modal(name + " 插件安装成功！", function (){
          window_history_refresh();
        });
      } else {
        show_fail_modal(ret.msg, function (){
          $("#modal-plugin-apps").modal('show');
        });
      }
    });
  }

  // 卸载插件
  function uninstall_plugin(id, name) {
    ajax_post("uninstall_plugin", {id: id}, function(ret){
      $("#modal-plugin-apps").modal('hide');
      if (ret.code === 0) {
        show_warning_modal(name + " 插件已卸载！", function (){
          window_history_refresh();
        });
      } else {
        show_fail_modal(ret.msg, function (){
          $("#modal-plugin-apps").modal('show');
        });
      }
    });
  }

</script>
<script type="text/javascript">
  $(document).ready(function(){
    fresh_tooltip();
  });
</script>
<script type="text/javascript">
  // 插件自带脚本函数
  {% for Id, Plugin in Plugins.items() %}
    {% if Plugin.script %}
      {{ Plugin.script|safe }}
    {% endif %}
  {% endfor %}
</script>